<?php
namespace app\admin\controller;
use Think\Controller;
use Think\Db;
use think\Request;
class Forms extends Common {
    //显示
    public function Index(){
        cookie('Jumpurl',basename($_SERVER['REQUEST_URI']));
        $db=Db("forms");
        $pagesize=input('pagesize',0);
        if($pagesize){
            $_SESSION['pagesizes']=$pagesizes=$pagesize;
        }else{
            if(isset($_SESSION['pagesizes'])){
                $pagesizes=$_SESSION['pagesizes'];
            }else{
                $pagesizes=10;
            }
        }
        $count = $db->count();
        // $Page = new \Think\AdminPage($count,10);
        // $show = $Page->show();
        $list = $db->paginate($pagesizes);
        // print_r($list);
        $this->assign('list',$list);
        // $this->assign('page',$show);
        return $this->fetch();

    }


    //添加
    public function Add(){
        $db=Db("forms");
        $id=input('id',0);
        $v=$db->find($id);
        if($v){

        }else{

        }
        if(request()->isPost()){
            $_POST['status']=1;
            $_POST['sendtime']=time();

            if(Request::instance()->isPost()){
                if($id){
                    if($db->save()!== false){
                        $title=input('title');
                        $tablename=input('tablename');
                        $oldtablename=input('oldtablename');
                        $sqls="rename table `".config('database.prefix')."{$oldtablename}` to `".config('database.prefix')."{$tablename}`";
                        $db->execute($sqls);

                        $sqlss="ALTER TABLE  `".config('database.prefix')."{$tablename}` CHANGE  `id` `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT  '{$title}表'";
                        $db->execute($sqlss);

                        // F("forms_{$id}",$_POST, TEMP_PATH);//存入缓存
                        $this->sys_log("编辑表单名称:{$title}(id:$id)");
                        $this->success("编辑成功",'/admin/forms/index.html');
                        exit();
                    }
                }else{
                    if($id=Db("forms")->insert($_POST)){
                        $title=input('title');
                        $tablename=input('tablename');
                        // F("forms_{$id}",$_POST, TEMP_PATH);//存入缓存

                        $sqls="CREATE TABLE `".config('database.prefix')."{$tablename}` (
                              `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '{$title}表',
                              `ip` varchar(15) NOT NULL DEFAULT '' COMMENT 'ip地址',
                              `status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '状态',
                              `sendtime` varchar(10) NOT NULL DEFAULT '' COMMENT '操作时间',
                              PRIMARY KEY (`id`),
                              KEY `{$tablename}` (`status`)
                            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
                        $db->execute($sqls);


                        $this->sys_log("添加表单名称:{$title}(id:$id)");
                        $this->success("添加成功",'/admin/forms/index.html');
                        exit();
                    }
                }
            }
            $this->error($db->getError());  
        }
        $this->assign("v",$v);
         return $this->fetch();
    }

    //显示
    public function Fields($typeid){
        cookie('Jumpurls',basename($_SERVER['REQUEST_URI']));
        $tablename=get_forms_zd($typeid);
        $list=Db()->query("SHOW FULL COLUMNS from `".config('database.prefix')."{$tablename}`");
        $pagesize=input('pagesize',0);
        if($pagesize){
            $_SESSION['pagesizes']=$pagesizes=$pagesize;
        }else{
            if(isset($_SESSION['pagesizes'])){
                $pagesizes=$_SESSION['pagesizes'];
            }else{
                $pagesizes=10;
            }
        }
        $field = Db($tablename)->paginate($pagesizes);

        foreach ($list as $k=>$v){
            $arr=explode("_",$v['Comment']);
            $list[$k]['title']=$arr[0];
            // $list[$k]['tip']=$arr[1];


        }
        // print_r(count($field));die;
        if(count($field)){
            $end= $field[count($field)-4];
            cookie('zd',$end);
        }
        
        $this->assign('list',$list);
        $this->assign('field',$field);
         return $this->fetch();
    }

    //显示
    public function Infos($typeid){
        $sqlkey='';
        $tablename=get_forms_zd($typeid);
        // echo $tablename;die;
        $db=Db("{$tablename}");
        $count = $db->count();
        $q=input('q');
        if($q) $sqlkey="tel='{$q}' ";
        // $Page = new \Think\AdminPage($count,10);
        // $show = $Page->show();
        $pagesize=input('pagesize',0);
        $page=input('page',0) ? intval(input('page',0)):1;
        if($pagesize){
            $_SESSION['pagesizes']=$pagesizes=$pagesize;
        }else{
            if(isset($_SESSION['pagesizes'])){
                $pagesizes=$_SESSION['pagesizes'];
            }else{
                $pagesizes=15;
            }
        }
        // 分页
        $show = $db->where($sqlkey)->paginate($pagesizes);
        $list = $db->where($sqlkey)->limit(($page-1)*$pagesizes,$pagesizes)->select();
        // print_r($list);die;
        foreach ($list as $k=>$v){
            if($v['status']==1) $status="<a href=\"/admin/forms/Audit/typeid/{$typeid}/id/{$v['id']}.html\"><img width=\"16\" height=\"16\" border=\"0\" alt=\"已启用\" src=\"/public/static/admin/images/p.png\"/></a>";else $status="<a href=\"/admin/forms/Audit/typeid/{$typeid}/id/{$v['id']}.html\"><img width=\"16\" height=\"16\" border=\"0\" alt=\"已查封\" src=\"/public/static/admin/images/x.png\"/></a>";
            $list[$k]['status']=$status;
            $list[$k]['sendtime']=date('Y-m-d',$v['sendtime']);
            
        }
        $this->assign('list',$list);
        $this->assign('page',$show);
         return $this->fetch();
    }

//添加
    public function InfoAdd($typeid){
        $id=input('id',0);
        $tablename=get_forms_zd($typeid);
        $db=Db("{$tablename}");
        unset($_POST['typeid']);
        $v=$db->find($id);
        if($v){
            
        }
        if(request()->isPost()){
            
            if(Request::instance()->isPost()){
                if($id){
                    if($db->update($_POST)){
                        // $this->sys_log("编辑{$v['catname']}栏目内容:{$v['title']}(id:$id)");
                        // $this->success("修改成功",cookie('Jumpurl'));
                        $this->success("修改成功",url("Forms/Infos?typeid={$typeid}"));
                        exit();
                    }
                }else{
                    $_POST['sendtime']=time();
                    $_POST['ip']=get_client_ip();
                    $_POST['status']=1;
                    if($id=$db->insert($_POST)){
                        $this->success("添加成功",url("Forms/Infos","typeid={$typeid}"));
                        exit();
                    }
                }

                
            }
            $this->error('失败');
        }
        $this->assign("v",$v);
        $this->assign("list");
        return $this->fetch('InfoAdd');
    }

    //添加
    public function FieldAdd(){
        $zd=cookie('zd');
        $typeid=input('typeid',0);
        if(request()->isPost()){
            
            $act=input('act');
            $tablename=input('table');
            $name=trim(input('name'));
            $title=trim($_POST['title']);
            $tip=trim(input('tip'));
            $typeid=input('typeid',0);
            if($act=='up'){
                $oldname=trim(input('oldname'));
                $sqls="ALTER TABLE  `".config('database.prefix')."{$tablename}` CHANGE  `{$oldname}` `{$name}` VARCHAR( 3000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  '' COMMENT '{$title}'";
                // exit($sqls);
                
                Db()->execute($sqls);
                $this->success("修改成功",url("Forms/Fields?typeid={$typeid}"));
                // $this->success("修改成功",cookie('Jumpurls'));
                exit();
            }else{
                $sqls="ALTER TABLE  `".config('database.prefix')."{$tablename}` ADD `{$name}` VARCHAR( 3000 ) NOT NULL DEFAULT  '' COMMENT  '{$title}_{$tip}' ";
                // exit($sqls);
                Db()->execute($sqls);
                $this->success("添加成功",url("Forms/Fields?typeid={$typeid}"));
                // $this->success("添加成功",cookie('Jumpurls'));
                exit();
            }

            $this->error(Db()->getError());
        }
        $this->assign("list");
        return $this->fetch('FieldAdd');
    }

    //更新
    public function FieldUpdate($typeid){
        $tablename=get_forms_zd($typeid);
        if(request()->isPost()){
            $oldname=trim(input('oldname'));
            $name=trim(input('name'));
            $title=trim(input('title'));
            $tip=trim(input('tip'));
            $pid=input('typeid',0);
            $sqls="ALTER TABLE  `".config('database.prefix')."{$tablename}` CHANGE  `{$oldname}` `{$name}` VARCHAR( 3000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  '' COMMENT '{$title}_{$tip}'";
            //exit($sqls);
            Db()->execute($sqls);
            $this->success("修改成功",url("Forms/Fields?typeid={$typeid}"));
            exit();
            $this->error(Db()->getError());
        }
         return $this->fetch();
    }

    //更新
    public function FieldDel($typeid){
        if(request()->isGet()){
            $tablename=get_forms_zd($typeid);
            $zd=trim(input('zd'));
            $sqls=" ALTER TABLE `".config('database.prefix')."{$tablename}` DROP `{$zd}`";
            Db()->execute($sqls);
            $this->success("删除成功",url("Forms/Fields?typeid={$typeid}"));
            exit();
            $this->error(Db()->getError());
        }
         return $this->fetch();
    }
    
    //审核
    public function Audit($typeid,$id){
        $tablename=get_forms_zd($typeid);
        $db=Db("{$tablename}");
        $list=$db->field("status")->find($id);
        $status=$list['status'];
        $_POST['id']=$id;
        $_POST['status']= $status ? 0 : 1;
        if(Request::instance()->isPost()){
            if($db->save()!== false){
                sys_log("审核表单:(id:$id)");
                $this->success("审核成功",url("Forms/Infos?typeid={$typeid}"));
                exit();
            }
        }   
        $this->error($db->getError());  
    }
    
    //删除
    public function formsdel(){
        $db=Db("forms");
        $id=input('id',0);
        
        if($id){
            $tablename=get_forms_zd($id);
           // echo $tablename;
            $sqls=" DROP TABLE `".config('database.prefix')."{$tablename}`";
            // exit($sqls);
            Db()->execute($sqls);
            // F("forms_{$id}",NULL,TEMP_PATH);//删除缓存

            if($db->delete($id)){
                $this->sys_log("删除表单:(id:$id)");
                $this->success("删除成功",'/admin/forms/index.html');
                exit();
            }else{
                $this->error("删除失败");
            }
        }else{
            $this->error('请选择删除信息!');
        }
    }

    //删除
    public function InfoDel($typeid){
        $tablename=get_forms_zd($typeid);

        $db=Db("{$tablename}");

        $did=$_POST['checkid'];

        if(!empty($did) && is_array($did)){
            $id=implode(",",$did);
            if($db->delete($id)){
                $this->success("删除成功！",url("Forms/Infos?typeid={$typeid}"));
            }else{
                $this->error("删除失败！");
            }
        }else{
            $this->error('请选择删除信息!');
        }

    }

     //删除
    public function Del(){
        $typeid=input('typeid');
        $tablename=get_forms_zd($typeid);
        $db=Db("{$tablename}");
        $id=input('id',0);
        if($id){
            if($db->delete($id)){
                $this->success("删除成功！",url("Forms/Infos?typeid={$typeid}"));
            }else{
                $this->error("删除失败！");
            }
        }else{
            $this->error('请选择删除信息!');
        }
    }

    //导出
    public function Genterdaochu($typeid){

            $name=Dbate("YmdHis");
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:filename={$name}.xls");
            $tablename=get_forms_zd($typeid);
            $list=Db()->query("SHOW FULL COLUMNS from `".config('database.prefix')."{$tablename}`");

            // print_r($list);

            $str.= "<table border='1' cellpadding='1' cellspacing='10'>";

            $str.= "<tr>";
                        foreach ($list as $k=>$v){
                            $arr=explode("_",$v['Comment']);
                            $list[$k]['title']=$arr[0];
                            $list[$k]['tip']=$arr[1];
                            if($v['Field']=='userpwd'||$v['Field']=='time'||$v['Field']=='ip'||$v['Field']=='status'||$v['Field']=='id'||$v['Field']=='img1'){
                                unset($list[$k]);
                            }else{
                                $str.="<th  bgcolor=\"#ffcc99\" >".$list[$k]['title']."</th>";
                            }
                        }
            $str.= "</tr>";
            
            $db=Db("{$tablename}");
            $count = $db->count();
            $Page = new \Think\AdminPage($count,10000);
            $show = $Page->show();
            $list2 = $db->limit($Page->firstRow)->select();
            // print_r($list2);
            foreach ($list2 as $k=>$v){
                
                
                $str.= "<tr>";
                foreach ($v as $key => $value) {
                    // echo '<pre>';
                    // print_r($key);  
                    if($key=='userpwd'||$key=='time'||$key=='id'||$key=='img1'||$key=='ip'||$key=='status'){
                        unset($v[$key]);
                    }else if($key=='sendtime'){
                        $str.="<th>".date("Y-m-d",$value)."</th>";
                    }else{
                        $str.="<th>".$value."</th>";
                    }
                }
                $str.= "</tr>";
            }
           
            $str.= "</table>";
            
            $return_data['status'] = 0;
            $return_data['msg'] = $str;
            $return_data['msg1'] = $name;

            // echo $str;
            echo json_encode($return_data);
            die;     
    }

    //导入
    public function daoru($typeid){
        $path="../".$upload_picpath."/";
        $p=(int)$_GET['pid'];
        $files=$_GET['files'];

        // 批量上傳商品的字段
        $_LANG['upload_goods']['title'] = '产品名称';
        $_LANG['upload_goods']['tags'] = '收藏编号';
        $_LANG['upload_goods']['introduce'] = '出品';
        $_LANG['upload_goods']['content'] = '监制';
        $_LANG['upload_goods']['price'] = '价格';
        $_LANG['upload_goods']['tel'] = '收藏人手机号';
        $_LANG['upload_goods']['name'] = '收藏人';
        $_LANG['upload_goods']['time'] = '出厂日期';
        $_LANG['upload_goods']['time2'] = '藏品年份';
        $_LANG['upload_goods']['xiangxing'] = '香型';
        $_LANG['upload_goods']['jiujing'] = '酒精度';
        $_LANG['upload_goods']['jinghan'] = '净含量';
        $_LANG['upload_goods']['shengchan'] = '生产';
        $_LANG['upload_goods']['introduce2'] = '内容摘要';
        $_LANG['upload_goods']['sendtime'] = '提交日期';
        // print_r($_LANG);die;
        function logResult($word='') {
            $fp = fopen("log.txt","a");
            flock($fp, LOCK_EX) ;
            fwrite($fp,$word."\n");
            flock($fp, LOCK_UN);
            fclose($fp);
        }

        /* 将文件按行读入数组，逐行进行解析 */
        $line_number = 0;
        $arr = array();
        $goods_list = array();
        $field_list = array_keys($_LANG['upload_goods']); // 字段列表
        $data = file($_FILES['file']['tmp_name']);
        if($_POST['data_cat'] == 'csv') {
            // print_r($data);die;
            
            foreach ($data AS $line){
                
                // 跳过第一行
                if ($line_number == 0||$line_number == 1)
                {
                    $line_number++;
                    continue;
                }

                $line = iconv("gb2312", 'UTF-8', $line);
        // print_r($line);die;
                // 初始化
                $arr    = array();
                $buff   = '';
                $quote  = 0;
                $len    = strlen($line);
                for ($i = 0; $i < $len; $i++)
                {
                    $char = $line[$i];

                    if ('\\' == $char)
                    {
                        $i++;
                        $char = $line[$i];

                        switch ($char)
                        {
                            case '"':
                                $buff .= '"';
                                break;
                            case '\'':
                                $buff .= '\'';
                                break;
                            case ',';
                                $buff .= ',';
                                break;
                            default:
                                $buff .= '\\' . $char;
                                break;
                        }
                    }
                    elseif ('"' == $char)
                    {
                        if (0 == $quote)
                        {
                            $quote++;
                        }
                        else
                        {
                            $quote = 0;
                        }
                    }
                    elseif (',' == $char)
                    {
                        if (0 == $quote)
                        {
                            if (!isset($field_list[count($arr)]))
                            {
                                continue;
                            }
                            $field_name = $field_list[count($arr)];
                            $arr[$field_name] = trim($buff);
                            $buff = '';
                            $quote = 0;
                        }
                        else
                        {
                            $buff .= $char;
                        }
                    }
                    else
                    {
                        $buff .= $char;
                    }

                    if ($i == $len - 1)
                    {
                        if (!isset($field_list[count($arr)]))
                        {
                            continue;
                        }
                        $field_name = $field_list[count($arr)];
                        $arr[$field_name] = trim($buff);
                    }
                }

                $goods_list[] = $arr;
                // echo "<pre>";
                // print_r($goods_list);
                // echo "</pre>";
            }
                 $m=0;
                 // print_r($goods_list);
                 // exit();
                if(count($goods_list)==0){
                    $this->error("请勿上传空数据！");exit();
                }
                foreach($goods_list as $k=>$v){
                    

                    $title=addslashes($v['title']);
                    $time2=addslashes($v['time2']);
                    $tags=addslashes($v['tags']);
                    $name=addslashes($v['name']);
                    $tel=addslashes($v['tel']);
                    $xiangxing=addslashes($v['xiangxing']);
                    $jiujing=addslashes($v['jiujing']);
                    $jinghan=addslashes($v['jinghan']);
                    $time=addslashes($v['time']);
                    $introduce=addslashes($v['introduce']);
                    $content=addslashes($v['content']);
                    $shengchan=addslashes($v['shengchan']);
                    $introduce2=addslashes($v['introduce2']);
                    $price=addslashes($v['price']);
                    if($v['sendtime']){
                        $sendtime=strtotime($v['sendtime']);
                    }else{
                        $sendtime=time();
                    }

                    
                    $str="`title`='{$title}',`time2`='{$time2}',`tags`='{$tags}',`name`='{$name}',`tel`='{$tel}',`xiangxing`='{$xiangxing}',`jiujing`='{$jiujing}',`jinghan`='{$jinghan}',`time`='{$time}',`introduce`='{$introduce}',`content`='{$content}',`shengchan`='{$shengchan}',`introduce2`='{$introduce2}',`price`='{$price}',`sendtime`='{$sendtime}',pid=1,ty=2,status=1";

                    $sqlkey="title='$title' and pid=1 and ty=2 ";
                    $count = D('news')->where($sqlkey)->count();
                    // echo $count;
                    if($count==0){
                         // $time = strtotime($material);
                        $sql="insert INTO `tp_news` SET {$str}";

                    }else{
                        // $sql="update `{$tablepre}product` SET {$str} where id={$id}";
                        // echo $sql."<br>";
                    }
                    // exit($sql);

                    if(D("news")->execute($sql)){
                        $m++;
                        // logResult();
                        // $this->success("{$m}成功");

                    }else{
                        // exit("失败".$sql);
                        exit("<script> alert(\"失败，数据重复了！\");window.location.href = '/Admin-News-Index-pid-1-ty-2.html';</script>！");
                        // echo $sql."<br>";

                    }

                    // echo $sql."<br>";
                }
                exit("<script> alert(\"导入完毕,共导入{$m}条数据\");window.location.href = '/Admin-News-Index-pid-1-ty-2.html';</script>！");
        }
    }

}

?>